//
//  HomeViewController.m
//  customer
//
//  Created by Holothurian on 2018/10/19.
//  Copyright © 2018年 yinlong. All rights reserved.
//

#import "HomeViewController.h"
#import "AgreementViewController.h"
#import "OneKeyRepairViewController.h"
#import "DesignAppointmentViewController.h"
#import "DecorateAppointmentViewController.h"
#import "DesignAppointmentViewController.h"
#import "CustomAdditionCaseListViewController.h"
#import "BaseWebViewViewController.h"
#import "BaseLocationManagerVC.h"

@interface HomeViewController (){
    NSArray *_sourceArray;
}

@property (nonatomic,strong)AdvertiseView *adV;

@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self baseSetting];
    
    [self layoutMainView];
    
    [self loadInitData];
}

- (void)baseSetting{
    self.title = @"一步e家";
    NSString * AgreementStr = K_UserDefault_Read(Customer_Agreement);
    if (k_Is_Empty(AgreementStr) || ![AgreementStr isEqualToString:@"是"] ) {
        AgreementViewController * vc = [[AgreementViewController alloc]init];
        vc.modalPresentationStyle = UIModalPresentationOverFullScreen;
        [self presentViewController:vc animated:YES completion:nil];
    }
}

- (void)layoutMainView{
    if (!self.adV) {
        self.adV = [self bannerView];
    }
    [self.view addSubview:self.adV];
    
    CGFloat bargin = 20;
    CGFloat leftBarginW = 15;
    CGFloat describeLeftBargin = 10;
    NSInteger itemWidth = (F_DEVICE_W - bargin - 2 * leftBarginW)/2.0;//itemView
    NSInteger itemHeight = (F_DEVICE_H - NAVIGATION_BAR_HEIGHT - TAB_BAR_HEIGHT - f_Ad_Content_H - 3 * bargin)/2.0;
    CGFloat subBargin = itemHeight * 0.1;
    CGFloat subBarginMin = itemHeight * 0.05;
    CGFloat imgWidth = itemHeight * 0.25;//imgView
    CGFloat imgLeftBargin = (itemWidth - imgWidth)/2.0;
    CGFloat describeHeight = itemHeight * 0.2;//describeLabel
    _sourceArray = @[@[@"oneKeyRepair",@"一键报修",@"专业团队为您\n排忧解难"],@[@"desigAppointment",@"设计预约",@"美学理念尽享\n品味生活"],@[@"decorateAppointment",@"装修预约",@"行业标杆打造\n人居典范"],@[@"customAdd",@"定制加配",@"个性定制彰显\n住宅潮流"]];
    AutoWeakSelf
    for (NSInteger i = 0; i < [_sourceArray count]; i++) {
        NSInteger line = i / 2;
        NSInteger column = i % 2;
        UIView *itemView = [[UIView alloc]init];
        itemView.layer.cornerRadius = leftBarginW;
        itemView.layer.masksToBounds = YES;
        itemView.tag = i + 100;
        itemView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:itemView];
        [itemView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(weakSelf.view.mas_left).offset(leftBarginW + column * (itemWidth + bargin));
            make.top.equalTo(weakSelf.adV.mas_bottom).offset(bargin + line * (itemHeight + bargin));
            make.size.mas_equalTo(CGSizeMake(itemWidth, itemHeight));
        }];
        
        UIImageView *imgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:_sourceArray[i][0]]];
        imgView.layer.cornerRadius = imgWidth/2.0;
        imgView.layer.masksToBounds = YES;
        imgView.userInteractionEnabled = YES;
        [itemView addSubview:imgView];
        [imgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(itemView.mas_top).offset(subBargin);
            make.left.equalTo(itemView.mas_left).offset(imgLeftBargin);
            make.size.mas_equalTo(CGSizeMake(imgWidth, imgWidth));
        }];
        
        UILabel *keyLabel = [[UILabel alloc]init];
        keyLabel.textAlignment = NSTextAlignmentCenter;
        keyLabel.textColor = [UIColor blackColor];
        keyLabel.font = [UIFont boldSystemFontOfSize:20];
        keyLabel.userInteractionEnabled = YES;
        keyLabel.text = _sourceArray[i][1];
        [itemView addSubview:keyLabel];
        [keyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(itemView).offset(describeLeftBargin);
            make.top.equalTo(imgView.mas_bottom).offset(subBargin);
            make.size.mas_equalTo(CGSizeMake(itemWidth - 2 * describeLeftBargin, subBargin));
        }];
        
        UILabel *describeLabel = [[UILabel alloc]init];
        describeLabel.text = _sourceArray[i][2];
        describeLabel.numberOfLines = 2;
        describeLabel.font = Font(14);
        describeLabel.userInteractionEnabled = YES;
        describeLabel.textColor = [UIColor textGrayColor];
        describeLabel.textAlignment = NSTextAlignmentCenter;
        [itemView addSubview:describeLabel];
        [describeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(itemView.mas_left).offset(describeLeftBargin);
            make.top.equalTo(keyLabel.mas_bottom).offset(subBarginMin);
            make.size.mas_equalTo(CGSizeMake(itemWidth - 2 * describeLeftBargin, describeHeight));
        }];
        
        UIImageView *rightArow = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"home_Right"]];
        rightArow.contentMode = UIViewContentModeScaleAspectFit;
        rightArow.userInteractionEnabled = YES;
        [itemView addSubview:rightArow];
        [rightArow mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(describeLabel.mas_bottom).offset(subBarginMin);
            make.centerX.equalTo(itemView);
            make.size.mas_equalTo(CGSizeMake(subBargin, subBargin));
        }];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
        [itemView addGestureRecognizer:tap];
    }
    
    [self refreshBanner:self.adV];
}


- (void)tapAction:(UITapGestureRecognizer *)tap{
    NSInteger index = tap.view.tag;
    switch (index) {
        case 100:{
            OneKeyRepairViewController *VC = [OneKeyRepairViewController new];
            TAB_PUSH(self, VC,YES);
        }break;
        case 101:{
            DesignAppointmentViewController *VC = [DesignAppointmentViewController new];
            TAB_PUSH(self, VC,YES);
        }break;
        case 102:{
            DecorateAppointmentViewController *VC = [DecorateAppointmentViewController new];
            TAB_PUSH(self, VC,YES);
        }break;
        case 103:{
            CustomAdditionCaseListViewController *VC = [CustomAdditionCaseListViewController new];
            TAB_PUSH(self, VC,YES);
        }break;
        default: break;
    }
   
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

//每次启动获取的一些动态数据
- (void)loadInitData {
    AutoWeakSelf
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:0];
    [dict setObject:[NSString emptyStr:K_UserDefault_Read(CustomerUserID)] forKey:@"member_id"];
    [dict setObject:[NSString emptyStr:K_UserDefault_Read(CustomerUserToken)] forKey:@"member_token"];
    [[QYNetManager sharedManager]POST:kGetMainTrailInfo parameters:dict andApiTyp:CustomerApiTypGetOrders SuccessBlock:^(id responseObject) {
        [weakSelf hideLoading];
        if ([responseObject[@"status"] isEqualToString:@"ok"]) {
            NSLog(@"%@",responseObject);
            NSDictionary *dic = responseObject[@"data"];
            NSDictionary *data = dic[@"data"];
            //报价参考url
            NSString *url = data[@"url"];
            //跑马灯
            NSString *message = data[@"info"];
            if (url != nil) {
                [[NSUserDefaults standardUserDefaults]setObject:url forKey:@"kSavedPriceHelpUrl"];
            }
            if (message != nil) {
                [[NSUserDefaults standardUserDefaults]setObject:message forKey:@"kSavedScrollMessage"];
            }
            [[NSUserDefaults standardUserDefaults]synchronize];
        }
        
    } Failure:^(NSError *error) {
        [weakSelf hideLoading];
        [weakSelf showErrorTipWithTitle:CustomerPoolNetStr];
    }];
}

@end

@implementation BaseViewController (advView)

- (AdvertiseView *)bannerView{
    return [[AdvertiseView alloc]initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, f_Ad_Content_W, f_Ad_Content_H)];
}

- (void)refreshBanner:(AdvertiseView *)adv{
    AutoWeakSelf
    __weak AdvertiseView *bAdv = adv;
    [self showLoading];
    [[QYNetManager sharedManager]POST:kGetYinlongBanners parameters:nil andApiTyp:CustomerApiTypGetOrders SuccessBlock:^(id responseObject) {
        [weakSelf hideLoading];
        if ([responseObject[@"status"] isEqualToString:@"error"]) {
            [weakSelf showErrorTipWithTitle:responseObject[@"error"]];
        }else{
            NSArray *dataList = responseObject[@"data"];
            [bAdv refreshWithItem:dataList FromType:(AdvertiseFromNetwork) CallBack:^(id  _Nonnull item) {
                if (item) {
                    
                    [weakSelf adClick:item];
                }
            }];
            [bAdv startAutoScroll:YES];

        }
        
    } Failure:^(NSError *error) {
        [weakSelf hideLoading];
        [weakSelf showErrorTipWithTitle:CustomerPoolNetStr];
    }];
    
}

/*
 private int banner_id;//
 private String banner_title;//标题
 private String banner_img;//图片路径
 private String banner_range;//1:用户 2:师傅
 private String banner_type;//0:无跳转 1:跳转外链
 private String chain_url;//外链网址
 private String sort;//排序
 private String is_delete;//1:删除
 private String create_time;//
 private String update_time;//
 */
- (void)adClick:(id)item{
    NSInteger banner_type = [[item objectForKey:@"banner_type"] integerValue];
    NSString *chain_url = [item objectForKey:@"chain_url"];
    NSString *banner_title = [item objectForKey:@"banner_title"];
    if (banner_type == 1) {
        BaseWebViewViewController *webView = [BaseWebViewViewController new];
        webView.urlStr = chain_url;
        webView.titleStr = banner_title;
        TAB_PUSH(self, webView,YES);
    }
//    else{
//        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提醒" message:banner_title?:@"" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
//        [alert show];
//    }
    
    
    
}
@end
